package avicit.bdp.dds.server.log;

import avicit.bdp.common.utils.SpringApplicationContext;
import avicit.bdp.dds.api.service.LoggerService;
import avicit.bdp.dds.common.Constants;
import avicit.bdp.dds.common.utils.LoggerUtils;
import avicit.bdp.dds.dao.entity.TaskLog;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.sift.AbstractDiscriminator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;

/**
 * @author admin
 * Task Log Discriminator
 */
public class TaskLogDiscriminator extends AbstractDiscriminator<ILoggingEvent> {
    private final Logger logger = LoggerFactory.getLogger(TaskLogDiscriminator.class);
    /**
     * key
     */
    private String key;

    /**
     * log base
     */
    private String logBase;

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");

    /**
     * logger name should be like:
     * Task Logger name should be like: Task-{processDefinitionId}-{processInstanceId}-{taskInstanceId}
     */
    @Override
    public String getDiscriminatingValue(ILoggingEvent event) {

        String loggerName = event.getLoggerName().split(Constants.EQUAL_SIGN)[1];
        String taskPrefix = LoggerUtils.TASK_LOGGER_INFO_PREFIX + Constants.HYPHEN;
        if (loggerName.startsWith(taskPrefix)) {
            storeLogToDb(event, loggerName);
            return loggerName.substring(taskPrefix.length(), loggerName.length() - 1).replace("-", "/");
        } else {
            return "unknown_task";
        }


    }

    /**
     * 保存日志到数据库
     *
     * @param event      event
     * @param loggerName loggerName
     */
    private void storeLogToDb(ILoggingEvent event, String loggerName) {
        LoggerService loggerService = SpringApplicationContext.getBean(LoggerService.class);
        String taskId = loggerName.split(Constants.HYPHEN)[3];
        taskId = taskId.substring(0, taskId.length() - 1);
        //数据开发日志保存到数据库
        try {
            String info = event.getFormattedMessage();
            TaskLog taskLog = new TaskLog();
            taskLog.setId(taskId);
            taskLog.setContents(info);
            taskLog.setTaskType("task");
            loggerService.insertTaskLog(taskLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void start() {
        started = true;
    }

    @Override
    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getLogBase() {
        return logBase;
    }

    public void setLogBase(String logBase) {
        this.logBase = logBase;
    }
}
